package com.heima.serch.service.impl;

import com.heima.common.exception.CustException;
import com.heima.feigns.BehaviorFeign;
import com.heima.model.behavior.pojos.ApBehaviorEntry;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.search.dtos.UserSearchDTO;
import com.heima.model.search.pojos.ApUserSearch;
import com.heima.model.search.vos.SearchArticleVO;
import com.heima.model.threadlocal.AppThreadLocalUtils;
import com.heima.model.user.pojos.ApUser;
import com.heima.serch.service.ApUserSearchService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.elasticsearch.common.recycler.Recycler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
@Slf4j
public class ApUserSearchServiceImpl implements ApUserSearchService {
    @Autowired
    MongoTemplate mongoTemplate;
    @Autowired
    BehaviorFeign behaviorFeign;
    @Async("taskExecutor") //此方法远程调用线程池  异步执行
    @Override
    public void insert(UserSearchDTO userSearchDto) {
    //1.校验参数 搜索词
        String searchWords = userSearchDto.getSearchWords();
        if (StringUtils.isBlank(searchWords)){
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID,"搜索词不存在");
        }
        //2.根据用户登录id 或 设备id 远程调用行为feign接口对应查询对应的行为实体数据
        ResponseResult<ApBehaviorEntry> behaviorResult = behaviorFeign.findByUserIdOrEquipmentId(userSearchDto.getEntryId(), userSearchDto.getEquipmentId());
        if (!behaviorResult.checkCode()){
            CustException.cust(AppHttpCodeEnum.REMOTE_SERVER_ERROR,"远程调用失败");
        }
        ApBehaviorEntry behaviorResultData = behaviorResult.getData();
        if (behaviorResultData==null){
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST,"行为实体不存在");
        }
        //3.根据行为实体的id 对应搜索词作为条件  查询是否已经有该历史记录
        Query query = Query.query(Criteria.where("entryId").is(userSearchDto.getEntryId()).and("keyword").is("searchWords"));
        ApUserSearch one = mongoTemplate.findOne(query, ApUserSearch.class);



        //3.1 如果有 修改时间
        if (one==null){
           one.setCreatedTime(new Date());
           mongoTemplate.save(one);
        }else {
            //3.2 如果没有就新增
            one =new ApUserSearch();
            one.setEntryId(behaviorResultData.getId());
            one.setKeyword(searchWords);
            one.setCreatedTime(new Date());
            mongoTemplate.save(one);
        }



    }

    @Override
    public ResponseResult findUserSearch(UserSearchDTO userSearchDto) {
        if(userSearchDto.getMinBehotTime() == null){
            userSearchDto.setMinBehotTime(new Date());
        }
        List<ApUserSearch> userSearchList = new ArrayList<>();
        int size = 10;
        ApUser user = AppThreadLocalUtils.getUser();
        //1 查询实体 60ed86609d88f41a1da5e770
        ResponseResult<ApBehaviorEntry> behaviorResult = behaviorFeign.findByUserIdOrEquipmentId(user==null?null:user.getId(), userSearchDto.getEquipmentId());
        if (behaviorResult.getCode().intValue()!=0) {
            CustException.cust(AppHttpCodeEnum.SERVER_ERROR,behaviorResult.getErrorMessage());
        }
        ApBehaviorEntry apBehaviorEntry = behaviorResult.getData();
        if (apBehaviorEntry == null) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        if (apBehaviorEntry != null) {
            // 查询当前用户的搜索列表  按照时间倒序 .limit(userSearchDto.getPageSize())
            userSearchList = mongoTemplate.find(Query.query(Criteria.where("entryId").is(apBehaviorEntry.getId()).and("createdTime").lt(userSearchDto.getMinBehotTime()))
                    .with(Sort.by(Sort.Direction.DESC,"createdTime")).limit(size),ApUserSearch.class);
            return ResponseResult.okResult(userSearchList);
        }
        return ResponseResult.okResult(userSearchList);
    }
}
